#include "stdio.h"
#include "stdlib.h"
#include "pthread.h"
#include "unistd.h"
#include "sys/types.h"

void *thread1_start(void *argv)
{
    pthread_t tid;

    tid = pthread_self();

    printf("thread1 start working, tid is %lu\n", tid);
    
    sleep(1);

    printf("thread1 finished, tid is %lu\n", tid);
    
    return argv;
}


void *thread2_start(void *argv)
{
    pthread_t tid;
    
    tid = pthread_self();
    
    printf("thread2 start working, tid is %lu\n", tid);

   // pthread_detach(tid);

    sleep(2);

    printf("thread2 finished, tid is %lu\n", tid);

    pthread_exit(argv);
}

int main()
{
    int ret1, ret2;
    pthread_t tid1, tid2;

    void *ret_val1, *ret_val2;
    
    ret1 = pthread_create(&tid1, NULL, thread1_start, "thread_name_1");
    ret2 = pthread_create(&tid2, NULL, thread2_start, "thread_name_2");

    if(ret1 || ret2){
        printf("create thread failed\n");
        return 0;
    }

    printf("main thread created 2 threads:\n tid1 is %lu, tid2 is %lu\n",tid1, tid2);

    ret1 = pthread_join(tid1, &ret_val1);
    ret2 = pthread_join(tid2, &ret_val2);

    printf("main thread join children threads:\n");
    printf("join thread1, result is %d\n", ret1);
    printf("join thread2, result is %d\n", ret2);

    printf("thread 1 exit value is %s\n", (char *)ret_val1);
    printf("thread 2 exit value is %s\n", (char *)ret_val2);

    return 0;
}
